// 数据持久化服务

import Dexie, { type Table } from 'dexie'
import type { GameState, SaveSlot } from '@/types'

export interface SaveData {
  id?: number
  slotId: string
  name: string
  gameState: GameState
  screenshot?: string
  createdAt: number
  updatedAt: number
  playTime: number
  version: string
}

export interface GameSettings {
  id?: number
  key: string
  value: any
  updatedAt: number
}

export interface GameStatistics {
  id?: number
  key: string
  value: number
  updatedAt: number
}

export class StarConquestDatabase extends Dexie {
  saves!: Table<SaveData>
  settings!: Table<GameSettings>
  statistics!: Table<GameStatistics>

  constructor() {
    super('StarConquestDB')
    
    this.version(1).stores({
      saves: '++id, slotId, name, createdAt, updatedAt',
      settings: '++id, &key, updatedAt',
      statistics: '++id, &key, updatedAt'
    })
  }
}

export const db = new StarConquestDatabase()

export class DatabaseService {
  private static instance: DatabaseService
  
  static getInstance(): DatabaseService {
    if (!DatabaseService.instance) {
      DatabaseService.instance = new DatabaseService()
    }
    return DatabaseService.instance
  }

  // 初始化数据库服务
  static async initialize(): Promise<void> {
    try {
      console.log('📊 初始化数据库连接...')
      
      // 确保数据库已打开
      await db.open()
      
      // 获取实例以确保单例模式正常工作
      const instance = DatabaseService.getInstance()
      
      // 检查数据库版本和完整性
      const dbInfo = await db.getDatabaseNames?.() || []
      console.log('📊 数据库连接成功，可用数据库:', dbInfo)
      
      // 初始化默认设置（如果不存在）
      await instance.initializeDefaultSettings()
      
      console.log('✅ 数据库服务初始化完成')
    } catch (error) {
      console.error('❌ 数据库初始化失败:', error)
      throw new Error(`数据库初始化失败: ${error instanceof Error ? error.message : '未知错误'}`)
    }
  }

  // 初始化默认设置
  private async initializeDefaultSettings(): Promise<void> {
    try {
      const defaultSettings = {
        'game.autoSave': true,
        'game.autoSaveInterval': 300000, // 5分钟
        'game.difficulty': 'normal',
        'display.theme': 'dark',
        'display.uiScale': 1.0,
        'display.animations': true,
        'audio.masterVolume': 0.8,
        'audio.musicVolume': 0.6,
        'audio.sfxVolume': 0.8,
        'notifications.enabled': true,
        'notifications.sound': true
      }

      for (const [key, value] of Object.entries(defaultSettings)) {
        const existing = await this.getSetting(key, null)
        if (existing === null) {
          await this.setSetting(key, value)
        }
      }
    } catch (error) {
      console.warn('⚠️ 初始化默认设置时出现警告:', error)
    }
  }

  // 存档管理
  async saveGame(slotId: string, name: string, gameState: GameState, screenshot?: string): Promise<boolean> {
    try {
      const now = Date.now()
      const existingSave = await db.saves.where('slotId').equals(slotId).first()
      
      const saveData: SaveData = {
        slotId,
        name,
        gameState: JSON.parse(JSON.stringify(gameState)), // 深拷贝
        screenshot,
        createdAt: existingSave?.createdAt || now,
        updatedAt: now,
        playTime: gameState.statistics.playTime,
        version: '1.0.0'
      }

      if (existingSave) {
        saveData.id = existingSave.id
        await db.saves.put(saveData)
      } else {
        await db.saves.add(saveData)
      }

      return true
    } catch (error) {
      console.error('保存游戏失败:', error)
      return false
    }
  }

  async loadGame(slotId: string): Promise<GameState | null> {
    try {
      const saveData = await db.saves.where('slotId').equals(slotId).first()
      return saveData ? saveData.gameState : null
    } catch (error) {
      console.error('加载游戏失败:', error)
      return null
    }
  }

  async deleteGame(slotId: string): Promise<boolean> {
    try {
      await db.saves.where('slotId').equals(slotId).delete()
      return true
    } catch (error) {
      console.error('删除存档失败:', error)
      return false
    }
  }

  async getAllSaves(): Promise<SaveSlot[]> {
    try {
      const saves = await db.saves.orderBy('updatedAt').reverse().toArray()
      return saves.map(save => ({
        id: save.slotId,
        name: save.name,
        screenshot: save.screenshot,
        lastSaved: save.updatedAt,
        playTime: save.playTime,
        gameVersion: save.version,
        isEmpty: false
      }))
    } catch (error) {
      console.error('获取存档列表失败:', error)
      return []
    }
  }

  async exportSave(slotId: string): Promise<string | null> {
    try {
      const saveData = await db.saves.where('slotId').equals(slotId).first()
      if (!saveData) return null
      
      return JSON.stringify(saveData, null, 2)
    } catch (error) {
      console.error('导出存档失败:', error)
      return null
    }
  }

  async importSave(saveDataJson: string): Promise<boolean> {
    try {
      const saveData: SaveData = JSON.parse(saveDataJson)
      
      // 验证数据格式
      if (!saveData.slotId || !saveData.gameState) {
        throw new Error('无效的存档格式')
      }

      // 生成新的slotId避免冲突
      const newSlotId = `imported_${Date.now()}`
      saveData.slotId = newSlotId
      saveData.updatedAt = Date.now()
      
      await db.saves.add(saveData)
      return true
    } catch (error) {
      console.error('导入存档失败:', error)
      return false
    }
  }

  // 设置管理
  async getSetting<T>(key: string, defaultValue: T): Promise<T> {
    try {
      const setting = await db.settings.where('key').equals(key).first()
      return setting ? setting.value : defaultValue
    } catch (error) {
      console.error('获取设置失败:', error)
      return defaultValue
    }
  }

  async setSetting<T>(key: string, value: T): Promise<boolean> {
    try {
      const now = Date.now()
      const existingSetting = await db.settings.where('key').equals(key).first()
      
      if (existingSetting) {
        await db.settings.put({
          id: existingSetting.id,
          key,
          value,
          updatedAt: now
        })
      } else {
        await db.settings.add({
          key,
          value,
          updatedAt: now
        })
      }
      
      return true
    } catch (error) {
      console.error('保存设置失败:', error)
      return false
    }
  }

  async getAllSettings(): Promise<Record<string, any>> {
    try {
      const settings = await db.settings.toArray()
      const result: Record<string, any> = {}
      
      settings.forEach(setting => {
        result[setting.key] = setting.value
      })
      
      return result
    } catch (error) {
      console.error('获取所有设置失败:', error)
      return {}
    }
  }

  // 统计数据管理
  async getStatistic(key: string): Promise<number> {
    try {
      const stat = await db.statistics.where('key').equals(key).first()
      return stat ? stat.value : 0
    } catch (error) {
      console.error('获取统计数据失败:', error)
      return 0
    }
  }

  async setStatistic(key: string, value: number): Promise<boolean> {
    try {
      const now = Date.now()
      const existingStat = await db.statistics.where('key').equals(key).first()
      
      if (existingStat) {
        await db.statistics.put({
          id: existingStat.id,
          key,
          value,
          updatedAt: now
        })
      } else {
        await db.statistics.add({
          key,
          value,
          updatedAt: now
        })
      }
      
      return true
    } catch (error) {
      console.error('保存统计数据失败:', error)
      return false
    }
  }

  async incrementStatistic(key: string, increment: number = 1): Promise<boolean> {
    try {
      const currentValue = await this.getStatistic(key)
      return await this.setStatistic(key, currentValue + increment)
    } catch (error) {
      console.error('增加统计数据失败:', error)
      return false
    }
  }

  async getAllStatistics(): Promise<Record<string, number>> {
    try {
      const statistics = await db.statistics.toArray()
      const result: Record<string, number> = {}
      
      statistics.forEach(stat => {
        result[stat.key] = stat.value
      })
      
      return result
    } catch (error) {
      console.error('获取所有统计数据失败:', error)
      return {}
    }
  }

  // 数据库维护
  async clearAllData(): Promise<boolean> {
    try {
      await db.saves.clear()
      await db.settings.clear()
      await db.statistics.clear()
      return true
    } catch (error) {
      console.error('清空数据库失败:', error)
      return false
    }
  }

  async getDatabaseSize(): Promise<number> {
    try {
      const saves = await db.saves.count()
      const settings = await db.settings.count()
      const statistics = await db.statistics.count()
      
      return saves + settings + statistics
    } catch (error) {
      console.error('获取数据库大小失败:', error)
      return 0
    }
  }

  async compactDatabase(): Promise<boolean> {
    try {
      // 删除过期的临时数据
      const oneWeekAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
      await db.saves.where('updatedAt').below(oneWeekAgo).and(save => 
        save.slotId.startsWith('temp_')
      ).delete()
      
      return true
    } catch (error) {
      console.error('压缩数据库失败:', error)
      return false
    }
  }
}